<?php

class Users_m extends CI_Model {
   
	function logout(){
		//echo '<pre>';print_r($this->session->userdata('userdata'));die;
		$this->session->sess_destroy();
		//force expire the cookie
		$this->generateCookie('[]', time()-3600);
	}

	private function generateCookie($data, $expire){
	  setcookie('User', $data, $expire, '/', $_SERVER['HTTP_HOST']);
	}

	function login($email, $password, $remember=false){
		$this->db->select('u.id,u.email,u.loai,cn.id canhan_id,cn.ho_ten,ntd.id ntd_id,ntd.ten ten_ntd');
		$this->db->from('users u');
		$this->db->join('canhan cn', 'u.id=cn.user_id','LEFT');
		$this->db->join('nhatuyendung ntd', 'u.id=ntd.user_id','LEFT');
		$this->db->where('u.email', $email);
		$this->db->where('u.trang_thai', 1);
		$this->db->where('u.password',  md5($password));
		$this->db->limit(1);
		$result = $this->db->get();
		// echo $this->db->last_query();die;
		$user   = $result->row_array();
		if($user){
			if($remember){
				 $loginCred = json_encode(array('email'=>$email, 'password'=>$password));
				 $loginCred = base64_encode($this->aes256Encrypt($loginCred));
				 //remember the user for 6 months
				 $this->generateCookie($loginCred, strtotime('+6 months'));
			}else{
				$tmp = array();
				$tmp['id']			= $user['id'];
				$tmp['email']		= $user['email'];
				$tmp['loai']		= $user['loai'];
				$tmp['canhan_id']	= $user['canhan_id'];
				$tmp['ho_ten']		= $user['ho_ten'];
				$tmp['ntd_id']		= $user['ntd_id'];
				$tmp['ten_ntd']	= $user['ten_ntd'];
				$this->session->set_userdata('userdata', $tmp);
			}			
			return true;
		}else{
			return false;
		}
	}

	function is_logged_in(){
		//check the cookie
		if(isset($_COOKIE['User'])){
			$info = $this->aes256Decrypt(base64_decode($_COOKIE['User']));
			$cred = json_decode($info, true);
			if(is_array($cred))
				return $this->login($cred['email'], $cred['password']);
		}
		$userdata = $this->session->userdata('userdata');
		if($userdata)
			return true;		
		return false;
	}

	function reset_password($email){
	  $this->load->library('encrypt');
	  $customer = $this->get_customer_by_email($email);
	  if ($customer)
	  {
			$this->load->helper('string');
			$this->load->library('email');
			
			$new_password       = random_string('alnum', 8);
			$customer['password']   = md5($new_password);
			$this->save($customer);
			
			$this->email->from($this->config->item('email'), $this->config->item('site_name'));
			$this->email->to($email);
			$this->email->subject($this->config->item('site_name').': Password Reset');
			$this->email->message('Your password has been reset to <strong>'. $new_password .'</strong>.');
			$this->email->send();
			
			return true;
	  }
	  else
	  {
			return false;
	  }
	}
	
	function change_password($password){
		$userdata = $this->session->userdata('userdata');
		if($userdata){
			$this->db->where('email', $userdata['email']);
			return $this->db->update('users', array('password'	=>	$password));
		}
		return false;
	}
	
   /**
    * Validate the login's data with the database
    * @param string $user_name
    * @param string $password
    * @return void
    */
   function validate($username, $password) {
      $this->db->where('username', $username);
      $this->db->where('password', $password);
		$this->db->where('status', 1);
      return $this->db->get('admins')->result();      
   }
   
   /**
    * Serialize the session data stored in the database, 
    * store it in a new array and return it to the controller 
    * @return array
    */
   function get_db_session_data() {
      $query = $this->db->select('userdata')->get('ci_sessions');
      $user  = array();
      /* array to store the user data we fetch */
      foreach ($query->result() as $row) {
         $udata                = unserialize($row->userdata);
         /* put data in array using username as key */
         $user['user_name']    = $udata['user_name'];
         $user['is_logged_in'] = $udata['is_logged_in'];
      }
      return $user;
   }
   
   /**
    * Store the new user's data into the database
    * @return boolean - check the insert
    */
   function create_user($data) {
      $this->db->insert('users', $data);
		return $this->db->insert_id();
   } //create_user
	
	function update_user($email, $password){
		$this->db->where('email', $email);
		$result = $this->db->update('users', array('password'=>md5($password)));
		if($result){
			$this->db->select("concat(IFNULL(cn.ho_ten,''),IFNULL(ntd.ten,'')) ho_ten",false);
			$this->db->join('canhan cn','cn.user_id = u.id','left');
			$this->db->join('nhatuyendung ntd','ntd.user_id = u.id','left');
			$this->db->where('email', $email);
			return 
			$this->db->get('users u')->row();
		}
		return false;
		echo $this->db->last_query();die;
	}
	
	function create_canhan($data) {      
		$this->db->insert('canhan', $data);		
		$id = $this->db->insert_id();
		$code = "HS".str_pad((int)$id, 5, "0", STR_PAD_LEFT);
		$this->db->where('id', $id);		
		$this->db->update('canhan', array('code'=>$code));	
		return $id;
   }
	
	function create_nhatuyendung($data){
		$this->db->insert('nhatuyendung', $data);
		return $this->db->insert_id();
	}
	
	function update_canhan($data, $user_id){
		$this->db->where('user_id', $user_id);
		return 
		$this->db->update('canhan', $data);
		echo $this->db->last_query();die;
	}
	
	function update_nhatuyendung($data, $user_id){
		$this->db->where('user_id', $user_id);
		return 
		$this->db->update('nhatuyendung', $data);
		echo $this->db->last_query();die;
	}
	
	private function aes256Encrypt($data){
		$key = config_item('encryption_key');
		if(32 !== strlen($key))
			$key = hash('SHA256', $key, true);
		$padding = 16 - (strlen($data) % 16);
		$data .= str_repeat(chr($padding), $padding);
		return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
	}
	private function aes256Decrypt($data){
		$key = config_item('encryption_key');
		if(32 !== strlen($key))
			$key = hash('SHA256', $key, true);
		$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
		$padding = ord($data[strlen($data) - 1]); 
		return substr($data, 0, -$padding); 
	}
		
	function get_current_user(){
		$userdata = $this->session->userdata('userdata');
		if($userdata){
			$this->db->select('u.email,cn.*');
			$this->db->from('users u');
			$this->db->join('canhan cn', 'cn.user_id=u.id');
			$this->db->where('u.trang_thai', 1);
			$this->db->where('u.email', $userdata['email']);
			return 
			$this->db->get()->row();
			//echo $this->db->last_query();die;
		}
		return false;
	}
	
	function get_user_by_type($type = 2, $return_array){
		$this->db->select('u.id,u.email,obj.ten');
		$this->db->from('users u');
		if($type == 1)
			$this->db->join('canhan obj', 'obj.user_id=u.id');
		else if($type == 2)
			$this->db->join('nhatuyendung obj', 'obj.user_id=u.id');
		$this->db->where('u.loai', $type);		
		$this->db->order_by('obj.ten', 'ASC');
		$result = $this->db->get()->result();
		if($return_array){
			$tmp = array();
			foreach($result as $obj)
				$tmp[$obj->id]	=	$obj->ten . ' - ' . $obj->email;			
			return $tmp;
		}
		return $result;
	}
	
	function get_current_admin(){
		$admin = $this->session->userdata('admin');
		if($admin) return $admin;
		return false;
	}
	
	function get_admin_user($id){
		$this->db->where('id', $id);
		return $this->db->get('admins')->row();
	}
	
	function delete_admin_user($id){
		$this->db->where('id', $id);
		$this->db->delete('admins');
	}
	
	function get_all_admins(){
		$this->db->order_by('username','ASC');
		return $this->db->get('admins')->result();
	}
	
	function update_admin($data){
		$admin = $this->session->userdata('admin');
		if($admin){
			$this->db->where('id', $admin['id']);
			return $this->db->update('admins', $data);
		}
		return false;
	}
	
	function save_admin_user($data){
		if(isset($data['id']) && $data['id']){
			$obj = $this->db->where('id', $data['id']);
			unset($data['id']);
			return 			
			$obj->update('admins', $data);
			// echo $this->db->last_query();die;
		}
		return $this->db->insert('admins', $data);
	}
	
	function check_admin_username($username){
		$this->db->where('username', $username);
		$row = $this->db->get('admins')->row();
		if($row) return true;
		return false;
	}
	
	function update_loai($data, $user_id){
		$this->db->where('id', $user_id);
		return $this->db->update('users', $data);
	}
	
	function active($id){
		$sql = "update users u inner join canhan cn
					on cn.user_id = u.id
					set u.trang_thai = 1
					where cn.id = $id";
		return 
		$this->db->query($sql);
	}
	
	function deactive($id){
		$sql = "update users u inner join canhan cn
					on cn.user_id = u.id
					set u.trang_thai = 0
					where cn.id = $id";
		return 
		$this->db->query($sql);
	}
}
